import React, { PureComponent } from 'react';
import { Form, Button, Upload, message, Card } from 'antd';
import $axios from '@/plugins/request'
import { withStorage } from "@/plugins/hoc";
const FormItem = Form.Item;
// @Form.create()
class Editimg extends PureComponent {
    state = {
        fileList: [],//存放上传信息：比如路径、文件名
        imgList: [],//存放回显信息：修改时的路径、文件名
    };

    //form表单提交事件
    handleSubmit = e => {
        const { dispatch, form } = this.props;
        e.preventDefault();
        form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                const { imgList } = this.state
                values.imgList = JSON.stringify(imgList);
                console.log('values', values);
            }
        });
    };

    //上传事件
    onChange = ({ fileList }) => {
        console.log('file', fileList);
        let userInfo = this.props.userInfo;
        console.log("userinfo", userInfo);
        let imgList = [];
        fileList.map(async (item, key) => {
            console.log("item", item);
            if (item.response && item.response.code === 1) {
                console.log("item.response", item.response);
                const { data: { src } } = item.response
                console.log('item.response', src?.[0]);
                imgList.push({ url: item.response.url, Name: item.response.name });//这的参数具体看上传成功后返回的值，打印的item.response

                const { data } = await $axios.put("/api/users/" + userInfo._id, { head: src?.[0] })
                if (data.code == 1) {
                    userInfo.head = src?.[0]
                    localStorage.setItem("userInfo", JSON.stringify(userInfo))
                    location.reload();
                    return message.success("上传成功")
                }
            } else {
                if (item.url) {
                    //拼接'http:// 如果路径可以直接使用不需要拼接
                    imgList.push({ url: item.url.replace('http://', ""), Name: item.name });

                }
            }
        });
        this.setState({ fileList, imgList });

    }
    render() {
        const { fileList } = this.state
        const props = {
            //name与接口需要的name一致
            name: 'image',
            action: '/api/upload',
            //接口需要的参数，无参数可以不写
            data: {},
            //展示文件列表
            showUploadList: true,
        }

        return (
            <Card title="修改头像" style={{ width: 400 }}>
                <Form onSubmit={this.handleSubmit}><FormItem label="上传头像">
                    <Upload {...props}
                        fileList={fileList}
                        onChange={this.onChange}
                    >
                        <Button>
                            上传附件
                        </Button>
                    </Upload>
                </FormItem>
                </Form>
            </Card>

        );
    }
}
Editimg = withStorage("userInfo")(Editimg)
export default Editimg